<?php
namespace app\common\controller;
use think\Config;
class Wechat
{
    //订单查询接口
    const QUERY = 'https://api.mch.weixin.qq.com/pay/orderquery';
    //H5统一下单接口
    const UNIFIED = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    /**
     * 发送post请求
     *
     * @param $data
     * @param $key
     * @param $url
     * @return bool|mixed|string
     */
    public function postCurl($data, $url)
    {
        $config = get_addon_config('epay');
        $key = $config['wechat']['key'];   //微信商户自定义密钥key为商户平台设置的密钥key
        $data['sign'] = $this->genSign($data, $key);    //生成微信sign签名
        $data = $this->array_to_xml($data);         //数组转XML格式数据
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $return = curl_exec($ch);
        curl_close($ch);
        $xml = simplexml_load_string($return, "SimpleXMLElement", LIBXML_NOCDATA);
        $data = json_decode(json_encode($xml), TRUE);
        return $data;
    }
    /**
     * 组建签名
     * @param array $params 请求参数
     * @param string $key 秘钥
     * @return string
     */
    public function genSign($params, $key)
    {
        foreach ($params as $k => $v) {
            if (!$v) {
                unset($params[$k]);
            }
        }
        ksort($params);
        $paramStr = '';
        foreach ($params as $k => $v) {
            $paramStr = $paramStr . $k . '=' . $v . '&';
        }
        $paramStr = $paramStr . 'key=' . $key;
        $sign = strtoupper(md5($paramStr));
        return $sign;
    }
    /**
     * 将数组转为XML
     * @param array $params 支付请求参数
     * @return bool|string
     */
    public function array_to_xml($params)
    {
        if (!is_array($params) || count($params) <= 0) {
            return false;
        }
        $xml = "<xml>";
        foreach ($params as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}